package com.mxf.code.product_coupon.strategy;

import com.mxf.code.product_coupon.domain.Coupon;
import com.mxf.code.product_coupon.domain.Member;
import com.mxf.code.product_coupon.domain.Product;

import java.math.BigDecimal;
import java.util.List;

/**
 * 提供了基本的价格计算方法，其中包括判断是否是会员、是否有优惠券、计算总价等方法
 */
public abstract class AbstractPriceCalculator {
    protected DiscountStrategy discountStrategy;
    protected FullReductionStrategy fullReductionStrategy;

    public AbstractPriceCalculator(DiscountStrategy discountStrategy, FullReductionStrategy fullReductionStrategy) {
        this.discountStrategy = discountStrategy;
        this.fullReductionStrategy = fullReductionStrategy;
    }

    protected BigDecimal getDiscountPrice(Product product, Member member) {
        return discountStrategy.calculateDiscountPrice(product, member);
    }

    protected BigDecimal getFullReductionPrice(List<Product> productList) {
        return fullReductionStrategy.calculateFullReductionPrice(productList);
    }

    protected boolean isMember(Member member) {
        return member != null && member.getLevel() > 0;
    }

    protected boolean hasCoupon(Coupon coupon) {
        return coupon != null && coupon.getAmount().compareTo(BigDecimal.ZERO) > 0;
    }

    public BigDecimal calculateTotalPrice(List<Product> productList, Member member, Coupon coupon) {
        BigDecimal totalPrice;
        for (Product product : productList) {
            if (isMember(member) && product.isMemberProduct()) {
                // 会员价
                BigDecimal discountPrice = getDiscountPrice(product, member);
                product.setPrice(discountPrice);
            }
        }
        // 满减
        totalPrice = getFullReductionPrice(productList);
        // 优惠券
        if (hasCoupon(coupon)) {
            totalPrice = totalPrice.subtract(coupon.getAmount());
        }
        return totalPrice;
    }
}
